package com.fulihui.wgj.service.mass;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.builder.rpc.RpcResultBuilder;
import com.fulihui.common.enums.CustomMsgTypeEnum;
import com.fulihui.common.enums.SendLogStatusEnum;
import com.fulihui.common.error.Errors;
import com.fulihui.common.error.InvokeServiceException;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.common.util.PlatformUtil;
import com.fulihui.wgj.biz.SendMassMsgBiz;
import com.fulihui.wgj.biz.WeiXinSdkBiz;
import com.fulihui.wgj.biz.WxUserInfoBiz;
import com.fulihui.wgj.dal.mybatis.domain.WxMassMsgLog;
import com.fulihui.wgj.dal.mybatis.domain.WxMaterial;
import com.fulihui.wgj.dal.mybatis.repository.WxMassMsgLogRepository;
import com.fulihui.wgj.dal.mybatis.repository.WxMaterialRepository;
import com.fulihui.wgj.facade.request.mass.CalcMassMsgRequest;
import com.fulihui.wgj.facade.service.mass.SendWxMassService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 图文发送记录Service
 *
 * @author wang_wx
 * @date 2018-08-01
 */
@Component
@Service(interfaceClass = SendWxMassService.class, version = "1.0.0", timeout = 5000)
public class SendWxMassServiceImpl implements SendWxMassService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendWxMassServiceImpl.class);

    @Autowired
    WxUserInfoBiz wxUserInfoBiz;

    @Autowired
    PlatformUtil platformUtil;

    @Autowired
    WeiXinSdkBiz weiXinSdkBiz;

    @Autowired
    WxMassMsgLogRepository wxMassMsgLogRepository;

    @Autowired
    WxMaterialRepository wxMaterialRepository;

    @Autowired
    SendMassMsgBiz sendTemplateMsg;

    @Override
    public BaseResult sendMassMsg(CalcMassMsgRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        String appId = request.getAppId();
        String token = platformUtil.get(appId);
        if (StringUtils.isBlank(token)) {
            LOGGER.warn("appId=[{}] ,s token is empty!");
            return RpcResultBuilder.fail(Errors.Commons.TOKEN_DOES_NOT_EXIST);
        }
        // 先判断素材是否已被微信后台删除
        String mediaId = request.getMediaId();
        Boolean isUseful = weiXinSdkBiz.mpMaterialIsUseful(token, mediaId);
        if (!isUseful) {
            return RpcResultBuilder.fail(Errors.WxMaterialError.MATERIAL_HAS_EXPIRED);
        }
        WxMaterial wxMaterial = wxMaterialRepository.queryById(mediaId);
        if (Objects.isNull(wxMaterial)) {
            return RpcResultBuilder.fail(Errors.WxMaterialError.MATERIAL_LOCAL_IS_NOT_FOUND);
        }

        Long recordCount = wxUserInfoBiz.queryCount(request);
        LOGGER.info("sendMassMsg Calculation:{}", recordCount);
        if (0 >= recordCount) {
            // 推送人数为0 不允许推送
            return RpcResultBuilder.fail(Errors.WxTemplateLogError.THE_CURRENT_APP_PUSHES_RECORD_EMPTY);
        }
        // 插入发送记录表
        WxMassMsgLog wxMassMsgLog = insertMassLog(request, recordCount);
        if (Objects.isNull(wxMassMsgLog) || Objects.isNull(wxMassMsgLog.getId())) {
            LOGGER.info("SendWxMassService sendMassMsg, wxMassMsgLogId is null!!!");
            return RpcResultBuilder.fail(Errors.WxTemplateLogError.TEMPLATE_LOG_RECORD_INSERT_ERROR);
        }
        if (!wxMassMsgLog.getJobStatus() && Objects.isNull(wxMassMsgLog.getJobTime())) {
            // 不是定时任务 立即发送
            LOGGER.info("sendMassMsg, send now!");
            sendTemplateMsg.sendMassMsg(request, wxMassMsgLog);
        }
        return RpcResultBuilder.succ();
    }

    @Override
    public BaseResult sendMassMsg4Job(CalcMassMsgRequest request) throws InvokeServiceException {
        Long recordId = request.getRecordId();
        if (Objects.isNull(recordId)) {
            LOGGER.warn("sendMassMsg4Job recordId is null , cannot send");
            return RpcResultBuilder.fail(Errors.WxTemplateLogError.ID_CANNOT_BE_EMPTY);
        }
        WxMassMsgLog wxMassMsgLog = wxMassMsgLogRepository.queryById(recordId);
        if (Objects.isNull(wxMassMsgLog)) {
            LOGGER.warn("sendMassMsg4Job wxMassMsgLog is null , cannot send");
            return RpcResultBuilder.fail(Errors.Commons.RECORD_NOT_EXISTS);
        }

        Long recordCount = wxUserInfoBiz.queryCount(request);
        LOGGER.info("sendMassMsg4Job Calculation:{}", recordCount);
        // 更新记录状态
        WxMassMsgLog wxMassMsgLogUpdate = new WxMassMsgLog();
        wxMassMsgLogUpdate.setId(recordId);
        wxMassMsgLogUpdate.setTotalCount(recordCount);
        wxMassMsgLogUpdate.setSendStartTime(new Date());
        wxMassMsgLogUpdate.setSendStatus(SendLogStatusEnum.pushing.getCode());
        wxMassMsgLogRepository.updateSelective(wxMassMsgLogUpdate);
        // 发送
        sendTemplateMsg.sendMassMsg(request, wxMassMsgLog);
        return RpcResultBuilder.succ();
    }

    /**
     * 插入记录表
     *
     * @param condition
     * @param recordCount
     * @return
     */
    private WxMassMsgLog insertMassLog(CalcMassMsgRequest condition, Long recordCount) {
        WxMassMsgLog wxMassMsgLog = new WxMassMsgLog();
        wxMassMsgLog.setAppId(condition.getAppId());
        wxMassMsgLog.setTitle(condition.getTitle());
        wxMassMsgLog.setMediaId(condition.getMediaId());
        wxMassMsgLog.setSendConditionDesc(condition.getSendConditionDesc());
        wxMassMsgLog.setSendCondition(JSON.toJSONString(condition));
        wxMassMsgLog.setJobStatus(condition.getCronTab());
        wxMassMsgLog.setJobTime(Objects.isNull(condition.getJobTime()) ? null : condition.getJobTime());
        if (condition.getCronTab()) {
            wxMassMsgLog.setSendStatus(SendLogStatusEnum.await.getCode());
        } else {
            wxMassMsgLog.setSendStatus(SendLogStatusEnum.pushing.getCode());
        }
        wxMassMsgLog.setTotalCount(recordCount);
        wxMassMsgLog.setFailTotal(0L);
        wxMassMsgLog.setSuccessTotal(0L);
        wxMassMsgLog.setSendStartTime(new Date());
        wxMassMsgLog.setSendEndTime(null);
        wxMassMsgLog.setMsgType(CustomMsgTypeEnum.mpnews.getCode());
        wxMassMsgLog.setAlreadyPush(0L);
        WxMaterial wxMaterial = wxMaterialRepository.queryById(condition.getMediaId());
        if (Objects.nonNull(wxMaterial)) {
            wxMassMsgLog.setMsgContent(wxMaterial.getContent());
        }
        wxMassMsgLog.setMsgContent(wxMaterial.getContent());
        wxMassMsgLogRepository.saveSelective(wxMassMsgLog);
        LOGGER.info("insertMassLog:{}", wxMassMsgLog);
        return wxMassMsgLog;
    }

}
